from hashlib import md5

import requests
import logging
from urllib.parse import urlparse, unquote

APP_SERVER_LIST = ["https://spa-1259460662.cos.accelerate.myqcloud.com/agefans/api/age.json",
                   "https://spa-1302566318.file.myqcloud.com/age.json", "https://www.age-api.com:8443/age.json"]

logger = logging.getLogger("AgeAppApi")


class AgeAppApi:
    HEADERS = {
        'user-agent': "okhttp/3.10.0"
    }

    def __init__(self):
        self.server = self.get_server()
        self.playKey = self.get_playKey()

    def get_server(self):
        """
        获取Agenfans服务器地址
        :return: 服务器Host
        """
        for url in APP_SERVER_LIST:
            try:
                data = requests.get(url=url, headers=self.HEADERS).json()
                url_pare = urlparse(data['nav'][0]['url'])
                return url_pare.scheme + "://" + url_pare.netloc
            except Exception as e:
                logger.exception(e)
        raise Exception("无法获取服务器地址！")

    def get_playKey(self):
        """
        获取playKey参数
        :return: 成功返回str，失败返回None
        """
        html = requests.get(self.server, headers=self.HEADERS).text
        index = 0
        for key in ['id=app', 'script', '=']:
            if index > -1:
                index = html.find(key, index)
            else:
                return None
        if index == -1:
            return None
        index += 1
        jsSrc = html[index: html.find('>', index)]
        jsText = requests.get(jsSrc, headers=self.HEADERS).text
        index = 0
        for key in ['playKey', '"']:
            if index > -1:
                index = jsText.find(key, index)
            else:
                return None
        if index == -1:
            return None
        index += 1
        return jsText[index: jsText.find('"', index)]

    def get_play(self):
        """
        获取播放地址获取服务接口
        :return:
        """
        return requests.get("https://api.agefans.app/v2/_getplay", headers=self.HEADERS).json()

    def get_detail(self, aid):
        """
        获取番剧信息
        https://服务器地址/#/play/{aid}/{ep_index}/{play_index}
        :param aid: 番剧ID
        """
        return requests.get(f"https://api.agefans.app/v2/detail/{aid}", headers=self.HEADERS).json()

    def get_kp(self, play_id, vid, kt):
        """
        生成加密参数
        :param play_id: PlayVid
        :param vid: PlayVid
        :param kt: ServerTime
        :return: 加密阐述kp字符串
        """
        data = str(kt) + "{|}" + str(play_id) + "{|}" + str(vid) + "{|}" + self.playKey
        return md5(data.encode('utf8')).hexdigest()

    def get_play_url(self, play_id, vid):
        """
        获取播放地址
        :param play_id: PlayId
        :param vid: PlayVid
        :return:
        """
        playData = self.get_play()
        kt = playData['ServerTime']
        return requests.get(playData['Location'], headers=self.HEADERS, params={
            'playid': play_id,
            'kp': self.get_kp(play_id, vid, kt),
            'vid': vid,
            'kt': kt
        }).json()

    def search(self, keyword, page=1):
        return requests.get("https://api.agefans.app/v2/search", headers=self.HEADERS,
                            params={
                                'query': keyword,
                                'page': page
                            }).json()